import { observable, action, makeAutoObservable } from 'mobx';
import { RouterStore } from 'mobx-react-router';
import request from '@utils/request';
import Cookies from 'js-cookie';
import { apis } from '@http/index';
import { reject } from 'lodash';
// import { withTranslation } from 'react-i18next/*';
interface loginParams{
  username: String
  password: String
}
class RootStore {
  routing: RouterStore;
  userInfo: any;
  globalConfig: any;

  constructor() {
    makeAutoObservable(this);

    this.routing = new RouterStore();
    this.userInfo = {};
    this.globalConfig = JSON.parse(sessionStorage.getItem('config')||'{}');
  }

  // iconfontUrl = '//at.alicdn.com/t/font_1992797_v3rgjfxaof.js'

  // 登录
  login(params:loginParams){
    return new Promise((resolve,reject)=>{
      request.post(apis.login,params).then((res)=>{
        resolve(res)
      }).catch((err)=>{
        reject(err)
      })
    })
    
  }

  // 页面加载时首先去验证是否还在登录状态,感觉这地方可以加上白名单（未验证准确性）
  validateLogin() {
    request.get(apis.validateLogin).then((res) => {
      if (res.status === 200) {
        this.fetchUserInfo();
      }
    });
  }

  fetchUserInfo() {
    const user_id = Cookies.get('user_id') || '';
    if (user_id) {
      request.get(apis.getUserInfo(user_id)).then((res) => {
        this.userInfo = res.data;
      });
    } else {
      console.warn('user_id is null');
      this.logout();
    }
  }

  async logout() {
    await request.get(apis.logout);
  }
}

export default RootStore;
